package com.example.smmlab1;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
@RequestMapping("user")
public class UserController extends BaseController{
    @RequestMapping("signIn")
    private String signIn(){//处理登录请求
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Connection connection = DB.getConnection();
        String sql = "select * from db_user.user where username = ? and password = ?";

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                request.getSession().setAttribute("username",username);
                return "redirect:/home.jsp";
            }else {
                request.getSession().setAttribute("error","用户名或密码错误");
                return "redirect:/index.jsp";
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DB.close(resultSet,preparedStatement,connection);
        }


    }
    @RequestMapping("signUP")
    private String signUp(){
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Connection connection = DB.getConnection();
        String sql = "insert into db_user.user(username,password) values(?,?)";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;


        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            preparedStatement.executeUpdate();

            preparedStatement = connection.prepareStatement("select last_insert_id()");
            resultSet = preparedStatement.executeQuery();
            resultSet.next();
            int id = resultSet.getInt(1);

            request.getSession().setAttribute("message","注册成功你的ID是：" + id);


            return "redirect:/index.jsp";

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DB.close(resultSet,preparedStatement,connection);
        }
    }
    @RequestMapping("signOut")
    private String signOut(){
        session.invalidate();
        return "redirect:/index.jsp";
    }

}
